from flask import Blueprint, request, jsonify, current_app
from utils.response import success, error
from qqmusic_api import search
from config import config
import asyncio

getUrl_bp = Blueprint("getUrl", __name__)


async def fetch_all_pages(keyword):
    all_results = []
    page = 1
    NUM_PER_PAGE = 100

    while True:
        print(f"正在获取第 {page} 页...")

        result = await search.search_by_type(
            keyword=keyword, num=NUM_PER_PAGE, page=page, credential=config.CREDENTIAL
        )
        current_app.logger.info(f"搜索结果: {result}")

        if not result:
            break

        new_list = [
            {
                "title": item.get("title") or "未知歌曲",
                "singer": (
                    item.get("singer")[0].get("name")
                    if item.get("singer") and len(item.get("singer")) > 0
                    else "未知歌手"
                ),
                "album": item.get("album", {}).get("name") or "未知专辑",
                "publish_date": item.get("time_public") or "未知时间",
            }
            for item in result
        ]

        all_results.extend(new_list)

        await asyncio.sleep(1.5)
        page += 1

    return all_results


@getUrl_bp.route("/search", methods=["POST"])
async def searchKeyword():
    """
    查询接口
    """
    if not request.is_json:
        return error(message="请求格式不正确")

    data = request.json
    keyword = data.get("keyword")
    if not keyword:
        return error(message="关键词是必填项")

    try:
        result = await fetch_all_pages(keyword)

        if not result:
            return error(message="未找到搜索结果")
        if result:

            current_app.logger.info(f"搜索结果: {result}")

            return success(data={"result": result}, message="搜索成功")

    except Exception as e:
        return error(message="注册失败：" + str(e))
